package cn.project.xigui.ex.handler;

import cn.project.xigui.ex.ServiceException;
import cn.project.xigui.web.JsonResult;
import cn.project.xigui.web.ServiceCode;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     * @param exception 异常
     * @return JsonResult类（状态码，描述）
     * @author 闫鑫飞
     */
    @ExceptionHandler
    private JsonResult serviceExceptionHandler(ServiceException exception){
        return JsonResult.fail(ServiceCode.ERROR,exception.getMessage());
    }

    /**
     * 处理Validation 框架的 BindException(一般为某项内容为null)
     * @param exception 异常
     * @return JsonResult类（状态码，描述）
     * @author 闫鑫飞
     */
    @ExceptionHandler
    private JsonResult BindExceptionHandler(BindException exception){
        String message = exception.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERROR_NOT_FOUNT,message);
    }

    /**
     * 处理Validation 框架的 MissingServletRequestParameterException(一般为某项内容为null)
     * @param exception 异常
     * @return JsonResult类（状态码，描述）
     * @author 闫鑫飞
     */
    @ExceptionHandler
    private JsonResult MissingServletRequestParameterExceptionHandler(MissingServletRequestParameterException exception){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("请输入");
        stringBuilder.append(exception.getParameterName());
        String message = stringBuilder.toString();
        return JsonResult.fail(ServiceCode.ERROR_NOT_FOUNT,message);
    }

    /**
     * 处理空指针异常
     * @param exception 异常
     * @return JsonResult类（状态码，描述）
     * @author 闫鑫飞
     */
    @ExceptionHandler
    private JsonResult NullPointerExceptionHandler(NullPointerException exception){
        String message = "空指针异常";
        return JsonResult.fail(ServiceCode.ERROR,message);
    }

    @ExceptionHandler
    private JsonResult throwableHandler(Throwable throwable){
        String message = "请检查控制台";
        throwable.printStackTrace();
        return JsonResult.fail(ServiceCode.ERROR,message);
    }


}
